/*
 moxl - Modular XML Library
 Copyright (c) 2007, Malcolm Sparks

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package moxl.tokenizer;

import moxl.reader.Location;

public class Token
{
	private TokenType type;
	private StringBuilder imageBuffer;
	private String image;
	private final Location location;
	private final Token previousToken;

	public Token(Location location, Token previousToken)
	{
		this.location = location;
		this.previousToken = previousToken;
	}

	public void append(int character)
	{
		if (imageBuffer == null)
		{
			if (image == null)
			{
				imageBuffer = new StringBuilder();
			}
			else
			{
				imageBuffer = new StringBuilder(image);
			}
		}
		imageBuffer.append((char) character);
		image = null;
	}

	public TokenType getType()
	{
		return type;
	}

	public String getImage()
	{
		if (image != null)
		{
			return image;
		}
		if (imageBuffer == null)
		{
			return null;
		}
		return image = imageBuffer.toString();
	}

	public void setTokenType(TokenType type)
	{
		this.type = type;
	}

	public Location getLocation()
	{
		return location;
	}

	public boolean isWhitespace()
	{
		if (imageBuffer == null)
		{
			return true;
		}
		return Character.isWhitespace(imageBuffer.charAt(0));
	}

	public String getPrintableImage()
	{
		if (isWhitespace())
		{
			return "(whitespace)";
		}
		else
		{
			return "'" + getImage() + "'";
		}

	}

	public Token getPrevious()
	{
		return previousToken;
	}

	public void setImage(String name)
	{
		image = name;
		imageBuffer = null;
	}

	public boolean isType(TokenType type)
	{
		return this.type.equals(type);
	}

	@Override
	public String toString()
	{
		if (isWhitespace())
		{
			return "{type:" + type + "}";
		}
		else
		{
			return "{type:" + type + ",image:" + getImage() + "}";
		}
	}

}
